#!/usr/bin/env python
# crdfshow - a simplistic command-line interface to RDFshow

import codecs
import locale
import optparse
import sys

import rdflib
import rdfshow


__version__ = '0.1.1'


# Replace stdout with an encoding-aware version.
sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout)


# Parse command-line options.
opt = optparse.OptionParser(
        usage=u'%prog [options] URI [URI...] <input.rdf >output.xxx',
        version=(u'crdfshow %s' % __version__))
opt.add_option('-v', '--verbose', action='store_true', dest='verbose',
               help='Be verbose')
opt.add_option('-t', '--template', action='append', type='string',
               dest='templates', metavar='FILE',
               help='Use templates from FILE (more than one can be specified)')
opt.add_option('-f', '--flavour', action='store', type='string',
               dest='flavour', metavar='FLAVOUR',
               help='Select a template with FLAVOUR for rendering')
(options, args) = opt.parse_args()

def mumble(s):
    if options.verbose:
        print >>sys.stderr, s

# Load templates.
if (options.templates is None) or (len(options.templates) < 1):
    opt.error(u'No templates specified.')
mumble(u'loading templates...')
tpl_set = rdfshow.TemplateSet()
for tpl_file in options.templates:
    try:
        f = open(tpl_file, 'r')
        n = tpl_set.add_from_code(unicode(f.read()))
        mumble(u'%d templates loaded from %s' % (n, tpl_file))
    except Exception, e:
        print >>sys.stderr, u'error loading template %s: %s' % (tpl_file, e)
        sys.exit()
    finally:
        f.close()

# Load input data.
mumble(u'loading input data...')
graph = rdflib.ConjunctiveGraph()
try:
    graph.parse(sys.stdin, format='xml')
except Exception, e:
    print >>sys.stderr, u'error loading input data: %s' % e
    sys.exit()
mumble(u'loaded %d triples' % len(graph))

# Determine the nodes to be processed.
if len(args) < 1:
    opt.error(u'No URIs to process.')
nodes = [rdflib.URIRef(arg) for arg in args]
mumble(u'processing %d nodes...' % len(nodes))

if len(nodes) == 1:
    tpl_set.render_node(nodes[0], graph, sys.stdout, options.flavour)
elif len(nodes) > 1:
    tpl_set.render_node_set(nodes, graph, sys.stdout, options.flavour)
